<template>
  <div>
    <div class="headBar">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="参数编号">
              <el-input v-model="form.parameter_id"
                        clearable
                        placeholder="请输入"
                        prefix-icon="el-icon-search"
                        type="text"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="参数名">
              <el-input v-model="form.parameter_mean"
                        clearable
                        placeholder="请输入"
                        prefix-icon="el-icon-search"
                        type="text"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="参数类别">
              <el-select v-model="form.parameter_class" placeholder="请选择参数类别">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="2">
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="Search">查询</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button icon="el-icon-refresh" type="success" @click="reset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="tableData">
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
        border
        max-height="520px"
        :row-class-name="tableRowClassName">
        <el-table-column
          label="参数编号"
          prop="parameter_id"
          width="130">
        </el-table-column>
        <el-table-column
          label="参数名称"
          prop="parameter_mean"
          width="180">
        </el-table-column>
        <el-table-column
          label="参数类别"
          prop="parameter_class"
          width="180">
        </el-table-column>
<!--        <el-table-column-->
<!--          label="类别代码"-->
<!--          prop="classCode"-->
<!--          width="80">-->
<!--        </el-table-column>-->
        <el-table-column
          label="参数单位"
          prop="parameter_dimension"
          width="100">
        </el-table-column>
<!--        <el-table-column-->
<!--          label="参数角度°"-->
<!--          prop="angle"-->
<!--          width="100">-->
<!--        </el-table-column>-->
<!--        <el-table-column-->
<!--          label="参数高度"-->
<!--          prop="height"-->
<!--          width="100">-->
<!--        </el-table-column>-->
        <el-table-column
          label="参数备注"
          prop="parameter_remark">
          <template v-slot="scope">
            <span v-if="scope.row.parameter_remark === ''">无</span>
            <span v-else>{{scope.row.parameter_remark}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="isManager" label="操作">
          <template v-slot="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20,30]"
        :total="totalRows"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="EditParamDialog" title="编辑参数" width="40%">
      <el-form ref="form" :model="parameter" label-width="80px" style="width: 80%">
        <el-form-item label="参数名称">
          <el-input v-model="parameter.parameter_mean"
                    clearable
                    placeholder="请输入"
                    type="text"
          ></el-input>
        </el-form-item>
        <el-form-item label="参数类别">
          <el-input v-model="parameter.parameter_class"
                    clearable
                    placeholder="请输入"
                    type="text"
          ></el-input>
        </el-form-item>
<!--        <el-form-item label="类别代码">-->
<!--          <el-input v-model="parameter.classCode"-->
<!--                    clearable-->
<!--                    placeholder="请输入"-->
<!--                    type="text"-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="参数单位">
          <el-input v-model="parameter.parameter_dimension"
                    clearable
                    placeholder="请输入"
                    type="text"
          ></el-input>
        </el-form-item>
<!--        <el-form-item label="参数角度°">-->
<!--          <el-input v-model="parameter.angle"-->
<!--                    clearable-->
<!--                    placeholder="请输入"-->
<!--                    type="text"-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="参数高度m">-->
<!--          <el-input v-model="parameter.height"-->
<!--                    clearable-->
<!--                    placeholder="请输入"-->
<!--                    type="text"-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="参数备注">
          <el-input v-model="parameter.parameter_remark"
                    clearable
                    placeholder="请输入"
                    type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="EditParamDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="AddParamDialog" title="新增参数" width="40%" top="10vh">
      <el-switch
        v-model="isBatch"
        active-color="#13ce66"
        active-text="添加单个"
        inactive-color="#ff4949"
        inactive-text="批量添加">
      </el-switch>
      <hr>
      <div v-if="isBatch">
        <el-form ref="form" :model="parameter" label-width="80px" style="width: 80%">
          <el-form-item label="参数编号">
            <el-input v-model="parameter.parameter_id"
                      clearable
                      placeholder="请输入"
                      type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="参数名称">
            <el-input v-model="parameter.parameter_mean"
                      clearable
                      placeholder="请输入"
                      type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="参数类别">
            <el-input v-model="parameter.parameter_class"
                      clearable
                      placeholder="请输入"
                      type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="类别代码">
            <el-input v-model="parameter.classCode"
                      clearable
                      placeholder="请输入"
                      type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="参数单位">
            <el-input v-model="parameter.parameter_dimension"
                      clearable
                      placeholder="请输入"
                      type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="参数角度°">
            <el-input v-model="parameter.angle"
                      clearable
                      placeholder="请输入"
                      type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="参数高度">
            <el-input v-model="parameter.height"
                      clearable
                      placeholder="请输入"
                      type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="参数备注">
            <el-input v-model="parameter.parameter_remark"
                      clearable
                      placeholder="请输入"
                      type="textarea"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-row>
          <el-col :span="12">
            <el-button size="medium" style="margin-left: 5%" type="success" @click="addParam">新增单个参数</el-button>
          </el-col>
          <el-col :span="12">
            <el-button size="medium" type="warning" @click="reset">重置表单</el-button>
          </el-col>
        </el-row>
      </div>
      <div v-else>
        <el-row>
          <el-col :span="12">
            <el-button size="medium" style="margin-left: 5%" type="primary" @click="downloadModel">下载批量模板
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-upload
              :auto-upload="false"
              :before-upload="beforeUpload"
              :limit="1"
              :on-change="handleChange"
              accept=".xls,.xlsx"
              action='#'
              class="upload-demo"
            >
              <el-button slot="trigger" size="medium" type="primary">选择文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
            </el-upload>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "parameterManage",
  data() {
    return {
      isBatch: true,
      isManager: false,
      EditParamDialog: false,
      AddParamDialog: false,
      loading: false,
      pageNum: 1,
      pageSize: 10,
      totalRows: 1,
      options: [
        {
          value: "生产指标",
          label: "生产指标"
        },
        {
          value: "气流指标",
          label: "气流指标"
        },
        {
          value: "炉热指标",
          label: "炉热指标"
        },
      ],
      fileList: [],
      form: {
        pageNow: 1,
        pageSize: 10,
        parameter_id: "",
        parameter_class: "",
        parameter_mean: "",
        parameter_dimension: "",
        parameter_remark: "",
        angle:'',
        height:''
      },
      parameter: {
        parameter_id: '',
        parameter_mean: '',
        parameter_dimension: '',
        parameter_class: '',
        parameter_remark: '',
        angle:'',
        height:''
      },
      tableData: [
        {
          parameter_id: '101',
          parameter_mean: '3701号电偶温度',
          parameter_dimension: '摄氏度',
          parameter_class: "炉壁内衬温度",
          parameter_remark: '',
        },
        {
          parameter_id: '102',
          parameter_mean: '3702号电偶温度',
          parameter_dimension: '摄氏度',
          parameter_class: "炉壁内衬温度",
          parameter_remark: '',
        },
        {
          parameter_id: '103',
          parameter_mean: '3703号电偶温度',
          parameter_dimension: '摄氏度',
          parameter_class: "炉壁内衬温度",
          parameter_remark: '',
        }
      ],
    }
  },
  methods: {
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 === 1) {
        return 'warning-row';
      }
    },

    // 上传前的文件验证
    beforeUpload(file) {
      // 验证文件类型
      const isExcelOrCsv =  file.type === 'application/vnd.ms-excel' ||
                            file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                            file.type === 'text/csv';
      if (!isExcelOrCsv) {
        this.$message.error('只能上传excel或csv文件！');
        return false; // 阻止上传
      }
      // 可以在这里添加其他验证逻辑，如大小限制等

      return true;
    },

    // 文件状态变化时处理，例如文件被添加或移除
    handleChange(file, fileList) {
      if (file.status !== 'uploading') {
        this.uploadFile(file.raw); // 调用上传方法
      }
    },
    async uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file); // 'file'是后端接收文件的参数名，需与后端约定
      try {
        const response = await this.$axios.post(this.$httpUrlParameter+'/uploadFile', formData, { // 使用axios发送POST请求，替换为你的接口地址
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressEvent => {
            // 进度条处理，可与handleProgress结合或单独处理
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            console.log(`Upload progress: ${percentCompleted}%`);
          }
        });
        if (response.data.code === 200) {
          this.$message.success('文件上传成功！');
          this.AddParamDialog = false;
          setTimeout(() => {
            console.log("异步加载，保证数据可查到")
          },500)
          this.loadData()
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error('上传错误:', error);
        this.$message.error('文件上传出错！');
      }
    },

    handleEdit(row) {
      this.EditParamDialog = true;
      this.parameter = row;
    },
    confirmEdit() {
      this.$axios.post(this.$httpUrlParameter + '/update', this.parameter).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.loadData()

          this.EditParamDialog = false;
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      }).catch(
        err => {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      )
      this.resetParam()
    },
    handleDelete(row) {
      this.$confirm('是否删除该条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post(this.$httpUrlParameter + '/delete', row).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '操作成功！',
              type: 'success'
            });
            this.loadData()
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch(
          err => {
            this.$message({
              message: '操作失败！',
              type: 'error'
            });
          }
        )
      })
    },
    Search(){
      this.pageNum = 1;
      this.loadData()
    },
    loadData() {
      this.loading = true;
      console.log(this.form);
      this.form.pageNow = this.pageNum;
      this.form.pageSize = this.pageSize;
      this.$axios.post(this.$httpUrlParameter + '/getByPage', this.form).then(res => {
        res = res.data
        if (res.code === 200) {
          this.tableData = res.data.rowData;
          this.totalRows = res.data.totalRows;

        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
        this.loading = false;
      }).catch(err => {
        this.$message({
          message: '加载数据失败！',
          type: 'error'
        });
        this.loading = false;
        }
      )
    },
    reset() {
      this.form.parameter_id = '';
      this.form.parameter_class = '';
      this.form.parameter_mean = '';
      this.form.parameter_dimension = '';
      this.form.parameter_remark = '';
      this.loadData()
    },
    resetParam(){
      this.parameter = {
        parameter_id: '',
        parameter_mean: '',
        parameter_dimension: '',
        parameter_class: '',
        parameter_remark: '',
      }
    },
    appendParam(){
      this.AddParamDialog = true;
      this.isBatch=true
      this.resetParam()
    },
    addParam() {
      this.$axios.post(this.$httpUrlParameter + '/add', this.parameter).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.loadData()
          this.AddParamDialog = false
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      }).catch(
        err => {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      )
    },
    downloadModel() {
      // 构建模板文件的URL
      const url = `${process.env.BASE_URL}parameterModel.xlsx`;

      // 创建隐藏的a标签来触发下载
      const link = document.createElement('a');
      link.href = url;
      link.style.display = 'none';
      link.download = 'parameterModel.xlsx'; // 设置下载文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    upload() {
      this.UploadDialog = true
    },
    derive() {
    //   TODO:将数据库内容导出

    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1
      this.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      this.loadData()
    },
  },
  mounted() {
    if(sessionStorage.getItem("UserStatue") === '2'){
      this.isManager = true
    }
    this.loadData()
  }
}

</script>

<style>
.el-table .warning-row {
  background: rgb(192, 226, 253);
}
.headBar {
  padding: 12px 0px 0px 18px;
  border-radius: 0 0 15px 15px;
  box-shadow: 0 2px 8px 2px rgba(0, 0, 0, 0.1);
}

.tableData {
  margin: 10px;
}
</style>
